﻿using System.Collections.Generic;
using CoreEx.Common.Validation;
using LinFu.IoC.Configuration;

namespace CoreEx.Common.Implementation.Validation
{
    /// <summary>
    /// Validates a list of validation rules.
    /// </summary>
    [Implements(typeof(IRulesValidator))]
    public class RulesValidator : IRulesValidator
    {
        /// <summary>
        /// Validates a list of <see cref="IValidationRule{T}"/> instances and returns
        /// the returns the error message from the first rule that is considered invalid.
        /// </summary>
        /// <typeparam name="T">The target type that the validation rules applies to.</typeparam>
        /// <param name="validationRules">The list of <see cref="IValidationRule{T}"/> instances to validate.</param>
        /// <param name="target">The target instance to validate.</param>
        /// <returns>A <see cref="string"/> that contains a textual representation of the broken rule, if any.</returns>
        public string Validate<T>(IEnumerable<IValidationRule<T>> validationRules, T target)
        {
            if (validationRules == null)
                return string.Empty;
            
            foreach (var validationRule in validationRules)
            {
                bool isValid = validationRule.Rule(target);
                if (!isValid)
                    return validationRule.Message;
            }
            return string.Empty;
        }
    }
}
